import 'dart:ui';

import 'package:flutter/material.dart';

///组合动画用法
///
///抽奖滚动动画 stack的组合
///
///
///
///

class PointOffset {
  Offset point;
  bool isEnd;
  static List<PointOffset> _pointOffset = <PointOffset>[];

  PointOffset.name(this.point, this.isEnd);
}

class CanvasPointScroll extends StatefulWidget {
  @override
  _CanvasPointScrollState createState() => _CanvasPointScrollState();
}

class _CanvasPointScrollState extends State<CanvasPointScroll> {
  //布局
  final GlobalKey containWidgetGlobalKey = GlobalKey();

  var _scrollController = ScrollController();
  double screenHeight = window.physicalSize.height;

  //画布
  late BoardPainterWidget canvasWidget;

  bool visible = false;

  @override
  void initState() {
    super.initState();

    // Init
    // _gestureDetectorHeight = screenHeight;
    _scrollController.addListener(() {
      print("画布滑动高度：${_scrollController.offset}");

      canvasWidget.getMoveDistance(_scrollController.offset);

      // setState(() {});
    });

    // WidgetsBinding.instance?.addPostFrameCallback((_) {
    //   _gestureDetectorHeight =
    //       containWidgetGlobalKey.currentContext?.size?.height;
    //   print("绘制完成：$_containHeight");
    //   setState(() {});
    // });

    Future.delayed(Duration(milliseconds: 5000), () {
      visible = true;

      setState(() {
      });
    });


    canvasWidget =  BoardPainterWidget(containWidgetGlobalKey);

  }



  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: SingleChildScrollView(
          controller: _scrollController,
          child: Stack(
            children: [
              Column(
                key: containWidgetGlobalKey,
                children: [
                  Container(
                    color: Color(0xFF15C9E8),
                    width: 400,
                    height: 400,
                  ),
                  Container(
                    color: Color(0xFF300C92),
                    width: 400,
                    height: 400,
                  ),
                  Container(
                    color: Color(0xFFB41C89),
                    width: 400,
                    height: 400,
                  ),
                  // TextButton(
                  //     onPressed: () {
                  //       print("按钮");
                  //     },
                  //     child: Text("data")),
                  Visibility(
                    visible: visible,
                    child: Container(
                      color: Color(0xFF1947EE),
                      width: 400,
                      height: 400,
                    ),
                  )
                ],
              ),
              canvasWidget
            ],
          ),
        ),
      ),
    );
  }
}


class BoardPainterWidget extends StatefulWidget {
  GlobalKey containWidgetGlobalKey;

  BoardPainterWidget(this.containWidgetGlobalKey);

  // void Function(double move)? callMoveBack;

   void getMoveDistance(double move){
      print("getMoveDistance--:$move");
      _state.getMoveDistance(move);
   }

  _BoardPainterWidgetState  _state = _BoardPainterWidgetState();


  @override
  _BoardPainterWidgetState createState() {
    return _state;
  }
}

class _BoardPainterWidgetState extends State<BoardPainterWidget> {
  /// 已描绘的点
  List<PointOffset> _pointOffset = <PointOffset>[];

  final GlobalKey containWidgetGlobalKey = GlobalKey();

  //一屏的高度
  double screenHeight = 0;
  //画布的高度
  double _gestureDetectorHeight = 0;
  //初始化测量出的widget试卷内容的高度
  double _containHeight = 0;

  void getMoveDistance(double move){
    //计算：初始化出的画布高度 -  一屏的高度 = 应该滚动到多少才是画布之外
    var otherHeight= _containHeight - screenHeight;
    print("getMoveDistance--:$move---otherHeight：$otherHeight----add--${move-otherHeight}");

    //move滚动的总距离- 应该滚动到多少才是画布之外 = 画布之外的高度
    if(move-otherHeight>0){
      //初始化测量出的widget试卷内容的高度 + 画布之外的高度 = 需要更新到的画布的高度
      _gestureDetectorHeight = _containHeight+move-otherHeight;
      print("画布高度：$_gestureDetectorHeight");

      setState(() {
      });
    }

  }

  /// 添加点，注意不要超过Widget范围
  _addPoint(DragUpdateDetails details) {
    // RenderObject? referenceBox = _globalKey.currentContext?.findRenderObject();
    // Offset localPosition = referenceBox?.globalToLocal(details.globalPosition);
    // double maxW = referenceBox.size.width;
    // double maxH = referenceBox.size.height;
    // // 校验范围
    // if (localPosition.dx <= 0 || localPosition.dy <= 0) return;
    // if (localPosition.dx > maxW || localPosition.dy > maxH) return;

    // Offset localPosition = details.localPosition;
    // setState(() {
    //   _points = List.from(_points)..add(localPosition);
    // });
    print("_addPoint $_gestureDetectorHeight");
    setState(() {
      _pointOffset = List.from(_pointOffset)
        ..add(PointOffset.name(details.localPosition, true));
    });
  }

  void moveCallback(double move){

  }


  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance?.addPostFrameCallback((_) {
      _gestureDetectorHeight =
          widget.containWidgetGlobalKey.currentContext?.size?.height??0;
      _containHeight = _gestureDetectorHeight;
      print("绘制完成：$_gestureDetectorHeight");
      setState(() {});
    });




  }


  @override
  Widget build(BuildContext context) {
    // final size =MediaQuery.of(context).size;
    // final width =size.width;
    // screenHeight =size.height;
    // print("绘制完成---：$screenHeight");

    return Stack(
      children: [
        Container(
          child: GestureDetector(
            onHorizontalDragUpdate: (details) => _addPoint(details),
            onHorizontalDragEnd: (details) {
              print("绘制 onPanEnd");
              _pointOffset.add(PointOffset.name(Offset.zero, false));
              // _points.add(Offset.zero);
            },
          ),
          height: _gestureDetectorHeight,
        ),
        CustomPaint(painter: BoardPainter(_pointOffset)),
      ],
    );
  }

//     return  Stack(
//       children: [
//         Container(
//           child: GestureDetector(
//             // onVerticalDragUpdate: (details){
//             //   setState(() {
//             //     _pointOffset = List.from(_pointOffset)..add(PointOffset.name(details.localPosition,true));
//             //   });
//             // },
//             // onVerticalDragEnd:  (details) {
//             //   print("绘制 onPanEnd");
//             //   _pointOffset.add(PointOffset.name(Offset.zero,false));
//             //   // _points.add(Offset.zero);
//             // },
//             onHorizontalDragUpdate: (details) => _addPoint(details),
//             onHorizontalDragEnd: (details) {
//               print("绘制 onPanEnd");
//               _pointOffset.add(PointOffset.name(Offset.zero, false));
//               // _points.add(Offset.zero);
//             },
//
//             // onPanUpdate: (details) => _addPoint(details),
//             // onPanEnd: (details) {
//             //   print("绘制 onPanEnd");
//             //   _pointOffset.add(PointOffset.name(Offset.zero,false));
//             //   // _points.add(Offset.zero);
//             // },
//           ),
//           height: _gestureDetectorHeight,
//         ),
//         CustomPaint(painter: BoardPainter(_pointOffset)),
//       ],
//     );
}

class BoardPainter extends CustomPainter {
  final Animation<double>? factor;

  BoardPainter(this.points, {this.factor}) : super(repaint: factor);

  final List<PointOffset> points;

  void paint(Canvas canvas, Size size) {
    // points.add(PointOffset.name(Offset(317,1455.8), true));
    // points.add(PointOffset.name(Offset(217,1479.8), true));
    Paint paint = Paint()
      ..color = Colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5.0;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null &&
          points[i + 1] != null &&
          points[i + 1].isEnd &&
          points[i].isEnd) {
        print("绘制 paint${points[i].point}----${points[i + 1].point}");

        canvas.drawLine(points[i].point, points[i + 1].point, paint);
      }
    }
  }

  bool shouldRepaint(BoardPainter other) {
    print("绘制 shouldRepaint--:${other.points != points}");
    return other.points != points;
  }
}
